from celery import shared_task

from django.utils import timezone
from django.db import transaction
from iClouds.apidev import has_Random
from mysqldb import tasks as TASKS
from mysqldb.models import (
    GameLolUseropenidList,
    AllinpayPlaceList,
    GameLolHonebaoList,
    GameLolHonebaoLogs,
)
from .serializers import GameLolChessListSerializer, GameLolRewardListSerializer
import json
import logging

logger = logging.getLogger(__name__)


@shared_task
def Q8doGameXiaguList(pid, data):
    """处理游戏数据 召唤师峡谷"""
    try:
        # data = eval(data)
        data = json.loads(data)
    except BaseException as err:
        logger.warn(f"[Games] [lol] [{pid}] 解析数据失败 {err}")
        raise ValueError(f"[Games] [lol] 解析数据失败 {err}")
    try:
        # mid = AllinpayMemberList.objects.get(
        #     idcode=hash_md5(data.get("UserID").upper()), pid=pid
        # )
        mid = GameLolUseropenidList.objects.get(userid=data.get("summonerId"))
    except BaseException as err:
        logger.warn(f"[Games] [lol] [{pid}] 查询会员失败 {err} {data}")
        raise ValueError(f"[Games] [lol] 查询会员失败 {err}")
    # mid = 1
    # 处理数据
    sess = {}
    sess["pid"] = pid
    sess["mid"] = mid.id
    sess["computername"] = data.get("jUserInfo_Json", {}).get("ComputerName")  # 机号
    sess["summonerid"] = data.get("summonerId")  # 游戏账号ID
    sess["summonername"] = data.get("summonerName")  # 召唤师名
    sess["area_cname"] = data.get("jUserInfo_Json", {}).get("area_cname")  # 大区信息
    sess["tier"] = data.get("jUserInfo_Json", {}).get("Tier")  # 段位等级
    sess["cn_champion"] = data.get("battle_ratio_json", {}).get("cn_Champion")  # 英雄名称
    sess["cn_gamemode"] = data.get("battle_ratio_json", {}).get("cn_GameMode")  # 游戏模式
    sess["cn_gametype"] = data.get("battle_ratio_json", {}).get("cn_GameType")  # 游戏类型
    sess["win"] = data.get("battle_ratio_json", {}).get("Win")  # 1 胜利；2 失败
    sess["winpoint"] = data.get("battle_ratio_json", {}).get("WinPoint")  # 胜点
    sess["start_time"] = data.get("battle_ratio_json", {}).get("start_time")  # 对局开始时间
    sess["stop_time"] = data.get("battle_ratio_json", {}).get("stop_time")  # 对局结束时间
    sess["lol_money"] = data.get("battle_ratio_json", {}).get("lol_money")  # 奖励金额基数
    sess["firstwin"] = data.get("battle_ratio_json", {}).get(
        "WB_FirstWinBonus_Multiple"
    )  # 首胜奖励倍数
    sess["seat_ratio"] = data.get("battle_ratio_json", {}).get("seat_ratio")  # 座位系数
    sess["tier_ratio"] = data.get("battle_ratio_json", {}).get("tier_ratio")  # 段位系数
    sess["time_ratio"] = data.get("battle_ratio_json", {}).get("time_ratio")  # 时间系数
    sess["area_ratio"] = data.get("battle_ratio_json", {}).get("area_ratio")  # 大区系数
    sess["type_ratio"] = data.get("battle_ratio_json", {}).get("type_ratio")  # 赛制系数
    sess["wx_money"] = data.get("battle_ratio_json", {}).get(
        "wx_money"
    )  # 红包金额 = 奖励金额*系数
    sess["status"] = 0
    sess["currentime"] = timezone.now()
    sess["code"] = has_Random()
    # sess = REDIS.clear_dict(sess)
    # 查询门店
    try:
        place = AllinpayPlaceList.objects.get(id=pid)
    except BaseException as err:
        p_name = ""
    else:
        p_name = place.basename
    try:
        r = GameLolHonebaoList(**sess)
        r.save()
    except BaseException as err:
        logger.warn(f"[Games] [lol] [{pid}] 创建记录失败 {err} {data}")
    else:
        # 写入成就记录
        try:
            lolog = [
                GameLolHonebaoLogs(
                    parent=r.id, **{key.lower(): value for key, value in args.items()}
                )
                for args in data.get("battle_ratio_json", {}).get("data", [])
            ]
            GameLolHonebaoLogs.objects.bulk_create(lolog)
        except BaseException as err:
            logger.warn(f"[Games] [lol] 创建对局数据失败 {err}")
        # 发送模板消息给会员
        if mid.openid:
            s = TASKS.WeAppsOpenidformSend(
                mid.openid,
                f"https://we.hs6686.com/#/lol?id={r.id}",
                "提现申请提交成功通知",
                [
                    p_name,
                    r.wx_money,
                    mid.name,
                    r.currentime.strftime("%Y年%m月%d日 %H:%M:%S"),
                ],
            )
    return {"rescode": 200, "resmsg": "success", "currenttime": timezone.now()}


@shared_task
def LOL_Chess_Data_Upload(*args, **kwargs):
    """lol 棋局数据上传"""
    logger.debug(f"[LOL] [接收数据] {kwargs}")
    # 取对局数据 dict()# 取成就奖励 dict()
    Chess = kwargs.pop("militaryExplotis")
    Reward = kwargs.pop("reward")
    # 合成数据
    data_chess = kwargs.copy()
    data_chess.update(Chess)

    data_reward = kwargs.copy()
    data_reward.update(Reward)

    db_chess = {k.lower(): v for k, v in data_chess.items()}
    db_reward = {k.lower(): v for k, v in data_reward.items()}

    # 显式开启事务
    with transaction.atomic():
        sid = transaction.savepoint()
        try:
            dcs = GameLolChessListSerializer(data=db_chess)
            if not dcs.is_valid():
                logger.warn(f"[LOL_valid_errors] {dcs.errors}")
                raise ValueError("验证错误")
            else:
                # logger.warn(f"[LOL_valid_success] {dcs.validated_data}")
                dcs.save()
            drs = GameLolRewardListSerializer(data=db_reward)
            if not drs.is_valid():
                logger.warn(f"[LOL_valid_errors] {drs.errors}")
                raise ValueError("验证错误")
            else:
                # logger.warn(f"[LOL_valid_success] {drs.validated_data}")
                drs.save()
        except BaseException as err:
            logger.warn(f"[LOL_data_error] {err}")
            transaction.savepoint_rollback(sid)
        else:
            transaction.savepoint_commit(sid)

    return {"rescode": 200, "resmsg": "success", "currenttime": timezone.now()}
